<template>
    <el-cascader
      :options="agentCascaderOptions"
      :props="{ checkStrictly: true }"
      :filterable="true"
      :placeholder="placeholder"
    />
  </template>
  
  <script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import type { OrganizationDto } from '@/utils/api/organization/type';
  import { getSelectAsync } from '@/utils/api/organization';
  import { propTypes } from '@/utils/propTypes';
  
  defineProps({
    placeholder: propTypes.string.def('请选择上级代理商')
  });
  
  /* 组织级联表 */
  interface CascaderOption {
    value: string;
    label: string;
    code: string;
    children?: CascaderOption[];
  }
  const agentCascaderOptions = ref<CascaderOption[]>([]);
  // 组织OrganizationSelect转化成Tree数组
  const convertSelectOrganization = (
    data: Array<OrganizationDto>,
    parentId?: string | null
  ): Array<CascaderOption> => {
    let arrays = new Array<CascaderOption>();
    let dataList = data
      .filter((it) => it.parentId === parentId)
      .sort(
        (a, b) =>
          parseInt(a.code.split('.')[a.code.split('.').length - 1]) -
          parseInt(b.code.split('.')[b.code.split('.').length - 1])
      );
    dataList.forEach((item) => {
      let tree: CascaderOption = {
        label: item.displayName,
        value: item.id,
        code: item.code,
        children: convertSelectOrganization(data, item.id)
      };
      arrays.push(tree);
    });
    return arrays;
  };
  // 初始化
  const initAgentSelectAsync = async () => {
    agentCascaderOptions.value = convertSelectOrganization(await getSelectAsync(true), null);
  };
  
  //组件挂载完毕
  onMounted(async () => {
    await initAgentSelectAsync();
  });
  </script>